﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using ArcGisMapDesktop.Models;

namespace ArcGisMapDesktop.Common
{
    public class WebHelper
    {
        private static string GetHttpContentType(string ext)
        {
            string cType = "image/jpeg";
            switch (ext.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    cType = "image/jpeg";
                    break;
                case ".png":
                    cType = "image/png";
                    break;
                case ".bmp":
                    cType = "image/bmp";
                    break;
                case ".gif":
                    cType = "image/gif";
                    break;
                default:
                    cType = "application/octet-stream";
                    break;
            }
            return cType;
        }

        /// <summary>
        /// 模拟http post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private static string CreateHttpPostResponse(string url, IDictionary<string, string> parameters)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";

            request.Headers.Add("X_MACHINE_ID", "ED5E3E2585B2477ABCA664EAAF32DC2A");
            request.Headers.Add("X_REG_SECRET", "er308343cf381bd4a37a185654035475d4c67842");
            request.Headers.Add("X_STORE", "0001");
            request.Headers.Add("X_BAY", "0001-01");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Accept-Language", "zh-CN");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.Accept = "*/*";

            request.CookieContainer = new CookieContainer();

            //如果需要POST数据   
            if (parameters != null && parameters.Count > 0)
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }

                //Encoding encoding = Encoding.GetEncoding("gb2312");
                Encoding encoding = Encoding.GetEncoding("utf-8");
                byte[] data = encoding.GetBytes(buffer.ToString());
                request.ContentLength = data.Length;
                request.GetRequestStream().Write(data, 0, data.Length);
            }
            else
            {
                request.ContentLength = 0;
            }
            string sReturnString = string.Empty;
            HttpWebResponse res;
            try
            {
                using (res = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        //读取服务器端返回的消息 
                        sReturnString = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {

                using (res = (HttpWebResponse)ex.Response)
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        //读取服务器端返回的消息 
                        sReturnString = sr.ReadToEnd();
                    }
                }
            }

            return sReturnString;
        }


        private static string CreateHttpGetResponse(string url, IDictionary<string, string> parameters)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }


            StringBuilder buffer = new StringBuilder();
            if (parameters != null && parameters.Count > 0)
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("?{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }
            HttpWebRequest request = WebRequest.Create(url + buffer.ToString()) as HttpWebRequest;
            request.Method = "GET";

            request.Headers.Add("X_MACHINE_ID", "ED5E3E2585B2477ABCA664EAAF32DC2A");
            request.Headers.Add("X_REG_SECRET", "er308343cf381bd4a37a185654035475d4c67842");
            request.Headers.Add("X_STORE", "0001");
            request.Headers.Add("X_BAY", "0001-01");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Accept-Language", "zh-CN");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.Accept = "*/*";

            request.CookieContainer = new CookieContainer();

            string sReturnString = string.Empty;
            HttpWebResponse res;
            try
            {
                using (res = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        //读取服务器端返回的消息 
                        sReturnString = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                using (res = (HttpWebResponse)ex.Response)
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        //读取服务器端返回的消息 
                        sReturnString = sr.ReadToEnd();
                    }
                }
            }
            return sReturnString;
        }

        public static string GetIP()
        {
            string ipv4 = String.Empty;
            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            if (ipv4 != String.Empty)
            {
                return ipv4;
            }
            // 利用 Dns.GetHostEntry 方法，由获取的 IPv6 位址反查 DNS 纪录，
            // 再逐一判断何者为 IPv4 协议，即可转为 IPv4 位址。
            foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            return ipv4;
        }

        public static T GetDataByUrl<T>(string url, out bool isOK, out string errorMsg)
        {
            url = FormatUrl(url);
            isOK = false;
            errorMsg = "";
            string html = WebHelper.CreateHttpGetResponse(url, null);
            CustomJsonResult response = html.ToObject<CustomJsonResult>();
            if (!response.Success)
            {
                isOK = false;
                errorMsg = response.Message;
                return default(T);
            }
            isOK = true;
            if (response.Data == null)
            {
                return default(T);
            }
            try
            {
                T t = JsonConvert.DeserializeObject<T>(response.Data.ToString());
                return t;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        public static T GetPostDataByUrl<T>(string url, Dictionary<string, string> paramDic, out bool isOK, out string errorMsg)
        {
            url = FormatUrl(url);
            isOK = false;
            errorMsg = "";
            string html = WebHelper.CreateHttpPostResponse(url, paramDic);
            CustomJsonResult response = html.ToObject<CustomJsonResult>();
            if (!response.Success)
            {
                isOK = false;
                errorMsg = response.Message;
                return default(T);
            }
            isOK = true;
            if (response.Data == null)
            {
                return default(T);
            }
            try
            {
                T t = JsonConvert.DeserializeObject<T>(response.Data.ToString());
                return t;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }


        public static string GetDataStrByUrl(string url, out bool isOK, out string errorMsg)
        {
            url = FormatUrl(url);
            isOK = false;
            errorMsg = "";
            string html = WebHelper.CreateHttpGetResponse(url, null);
            CustomJsonResult response = html.ToObject<CustomJsonResult>();
            if (!response.Success)
            {
                isOK = false;
                errorMsg = response.Message;
                return "";
            }
            isOK = true;
            return response.Message;
        }

        public static string GetPostDataStrByUrl(string url, Dictionary<string, string> paramDic, out bool isOK, out string errorMsg)
        {
            url = FormatUrl(url);
            isOK = false;
            errorMsg = "";
            string html = WebHelper.CreateHttpPostResponse(url, paramDic);
            CustomJsonResult response = html.ToObject<CustomJsonResult>();
            if (!response.Success)
            {
                isOK = false;
                errorMsg = response.Message;
                return "";
            }
            isOK = true;
            return response.Message;
        }

        private static string FormatUrl(string apiAction)
        {
            return ConfigurationManager.AppSettings["PreUrl"].TrimEnd('/') + "/api/" + apiAction;
        }
    }
}
